from django.conf import settings
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from itsdangerous import TimedJSONWebSignatureSerializer
from redis import StrictRedis
from rest_framework.exceptions import ValidationError
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializer
from users.models import User
from users.serializers import CreateUserSerializer, UserDetailSerializer, EmailSerialiezr, UserAddressSerializer, \
    AddBrowseHistorySerializer


class TestView0(View):
    def get(self, request):
        # a = 1/0
        return render(request, "test.html")


class TestView1(APIView):
    def get(self, request):
        response = Response({'message': 'get请求'})
        # response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8080'
        return response

    def post(self, request):
        response = Response({'message': 'post'})
        # response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8080'
        return response


# url: /usernames/admin/count/
class UsernameCountView(APIView):
    """验证用户名是否重复"""

    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        context = {
            'username': username,
            'count': count
        }
        return Response(context)


# url: /Usermobile/13000000000/count/
class UsermobileCountView(APIView):
    """验证j手机号是否重复"""

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        context = {
            'mobile': mobile,
            'count': count
        }
        return Response(context)


# url: /users/
class CreateUserView(CreateAPIView):
    """用户注册"""
    serializer_class = CreateUserSerializer


# url: /user/
class UserDetailView(RetrieveAPIView):
    """用户详情视图"""
    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]  # 制定权限，需要用户登录后才可以访问的路由视图

    def get_object(self):
        """需要指定是哪个用户，自定义get_object方法查指定出这个用户"""
        return self.request.user


# /email/
class EmailView(UpdateAPIView):
    """保存用户邮箱"""
    serializer_class = EmailSerialiezr
    permission_classes = [IsAuthenticated]  # 制定权限，需要用户登录后才可以访问的路由视图

    def get_object(self):
        """需要指定是哪个用户，自定义get_object方法查指定出这个用户"""
        return self.request.user


# url: /email/verification/?token=
class VerifyEmailView(APIView):
    """激活邮箱,修改email_active字段
    1. 获取请求参数： token
    2. 校验token合法性
    3. 从token中获取： user_id, email
    4. 查询出要激活的用户对象
    5. 修改用户对象的激活字段为true:  email_active=True
    6. 响应数据： {'message': 'ok'}
    """

    def get(self, request):
        # 1. 获取请求参数： token
        token = request.query_params.get('token')
        print('token', token)
        if not token:
            raise ValidationError({'message': 'token不能为空'})
        # 2. 校验token合法性
        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY)
        try:
            dict_data = serializer.loads(token)
        except:
            raise ValidationError({'message': 'token不合法'})
        # 3. 从token中获取： user_id, email
        user_id = dict_data.get('user_id')
        email = dict_data.get('email')
        # print('email',email)
        # 4. 查询出要激活的用户对象
        try:
            user = User.objects.get(id=user_id, email=email)
            # print('user', user)
        except User.DoesNotExist:
            raise ValidationError({'message': '用户不存在'})
        # 5. 修改用户对象的激活字段为true
        user.email_active = True
        user.save()
        # print('user', user)
        # 6. 响应数据： {'message': 'ok'}
        return Response({'message': 'OK'})


class AddressViewSet(CreateModelMixin, GenericViewSet):
    """用户地址管理
    地址的增删改查，设置默认地址，设置地址标题
    """
    serializer_class = UserAddressSerializer
    permission_classes = [IsAuthenticated]  # 制定权限，需要用户登录后才可以访问的路由视图

    def get_queryset(self):
        # 获取当前用户的所有地址
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        count = request.user.addresses.count()
        if count >= 3:  # 每个用户最多可以添加3个地址
            return Response({'message': '地址个数已达到上限'}, status=400)
        return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        """ 用户地址列表数据 """
        queryset = self.get_queryset()  # 当前登录用户的所有地址
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'user_id': request.user.id,
            'default_address_id': request.user.default_address_id,
            'limit': 3,
            'addresses': serializer.data  # 列表
        })


# 路由： POST  /browse_histories/
class BrowseHistoryView(CreateAPIView):
    """商品浏览历史记录"""

    permission_classes = [IsAuthenticated]
    serializer_class = AddBrowseHistorySerializer

    # 实际上并没有使用到此查询集, 但是不添加, 通过drf模板界面测试时会报错,
    # 通过前端axios发请求调用, 不会报错
    queryset = SKU.objects.all()

    # 接口1: 保存历史记录
    # def post(self, request, *args, **kwargs):
    #     return super().post(request, *args, **kwargs)

    def get(self, request):
        """接口2: 查询用户商品浏览历史记录"""

        # 获取用户id
        user_id = request.user.id

        strict_redis = get_redis_connection('history')  # type: StrictRedis
        # 从redis中查询所有的商品id
        sku_ids = strict_redis.lrange('history_%s' % user_id, 0, -1)

        sku_list = []
        # 从mysql查询商品对象
        # select * from xx where id in [1, 2, 3]
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        # 对商品sku对象进行序列化
        s = SKUSerializer(sku_list, many=True)
        # 响应数据
        return Response(s.data)


class UserAuthorizeView(ObtainJSONWebToken):
    """登录接口"""
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        s = self.get_serializer(data=request.data)  # 创建了一个序列化器对象, 接收请求的用户名和密码
        if s.is_valid():   # 返回true, 表示用户名和密码是正确的
            # 合并购物车中的商品
            # user = request.user                   # error, 获取不到用户对象
            user = s.validated_data.get('user')     # 从序列化器中获取用户对象
            merge_cart_cookie_to_redis(request, response, user)

        return response

